import Types from '../types'
import DataStore, { FLAG_STORAGE } from '../../expand/dao/DataStore'
import { _projectModels, handleData } from '../ActionUtil'

/**
 * 获取最热数据的异步action
 * @param storeName
 * @param url
 * @param pageSize  每页显示数目条数
 * @param favoriteDao
 * @return {Function}
 */
export function onRefreshPopular(storeName, url, pageSize, favoriteDao) {
	return dispatch => {
		dispatch({ type: Types.POPULAR_REFRESH, storeName: storeName })
		let dataStore = new DataStore()
		//异步action与数据流
		dataStore
			.fetchData(url, FLAG_STORAGE.flag_popular)
			.then(data => {
				handleData(
					Types.POPULAR_REFRESH_SUCCESS,
					dispatch,
					storeName,
					data,
					pageSize,
					favoriteDao
				)
			})
			.catch(error => {
				console.log(error)
				dispatch({
					type: Types.POPULAR_REFRESH_FAIL,
					storeName: storeName,
					error: error
				})
			})
	}
}

/**
 * 加载更多
 * @param storeName
 * @param pageIndex 第几页
 * @param pageSize  每页展示条数
 * @param dataArray 原始数据
 * @param favoriteDao
 * @param callback  回调函数，可以通过回调函数来向调用页面通信：比如异常信息的展示，没有更多
 */
export function onLoadMorePopular(
	storeName,
	pageIndex,
	pageSize,
	dataArray = [],
	favoriteDao,
	callback
) {
	return dispatch => {
		//模拟网络请求
		setTimeout(() => {
			if ((pageIndex - 1) * pageSize >= dataArray.length) {
				//已加载完所有数据
				if (typeof callback === 'function') {
					callback('no more')
				}
				dispatch({
					type: Types.POPULAR_LOAD_MORE_FAIL,
					error: 'no more data',
					storeName: storeName,
					pageIndex: --pageIndex
				})
			} else {
				//本次和载入的最大数量
				let max =
					pageSize * pageIndex > dataArray.length
						? dataArray.length
						: pageSize * pageIndex

				_projectModels(dataArray.splice(0, max), favoriteDao, data => {
					dispatch({
						type: Types.POPULAR_LOAD_MORE_SUCCESS,
						storeName: storeName,
						pageIndex: pageIndex,
						projectModels: data
					})
				})
			}
		}, 500)
	}
}

/**
 * 刷新收藏状态
 * @param storeName
 * @param pageIndex 第几页
 * @param pageSize 每页展示条数
 * @param dataArray 原始数据
 * @param favoriteDao
 */
export function onFlushPopularFavorite(
	storeName,
	pageIndex,
	pageSize,
	dataArray = [],
	favoriteDao
) {
	return dispatch => {
		let max =
			pageSize * pageIndex > dataArray.length
				? dataArray.length
				: pageSize * pageIndex

		_projectModels(dataArray.splice(0, max), favoriteDao, data => {
			dispatch({
				type: Types.FLUSH_POPULAR_FAVORITE,
				storeName: storeName,
				pageIndex: pageIndex,
				projectModels: data
			})
		})
	}
}
